package com.gitee.wsl.mathematics.geometry.d2.contour.segment.ext

import com.gitee.wsl.mathematics.geometry.d2.contour.segment.Segment2D
import com.gitee.wsl.mathematics.geometry.d2.contour.segment.fcurve.getCubicRoots


/**
 * Find the (first) t value for a given [x] value
 */
fun Segment2D.tForX(x: Double): Double {
    if (x == start.x.toDouble()) return 0.0
    if (x == end.x.toDouble()) return 1.0

    if (linear) {
        return (x - start.x) / (end.x - start.x)
    } else {
        val cb = this.cubic
        val a = cb.start.x - x
        val b = cb.control[0].x - x
        val c = cb.control[1].x - x
        val d = cb.end.x - x

        val t = getCubicRoots(a, b, c, d).firstOrNull() ?: 0.0

        return t
    }
}

/**
 * Find the y value for a given [x] value
 */
fun Segment2D.yForX(x: Double): Double {
    val t = tForX(x)
    return position(t.toFloat()).y.toDouble()
}
